package com.yi.mall.factory.predicate;

import jakarta.validation.constraints.NotEmpty;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class VipRoutePredicateFactory extends AbstractRoutePredicateFactory<VipRoutePredicateFactory.Config> {
    public VipRoutePredicateFactory() {
        super(VipRoutePredicateFactory.Config.class);
    }
    // 支持短参数配置
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param", "value");
    }
    public Predicate<ServerWebExchange> apply(final Config config) {
        return new GatewayPredicate() {
            public boolean test(ServerWebExchange exchange) {
                // 获取请求参数
                String param = exchange.getRequest().getQueryParams().getFirst(config.getParam());
                // 如果参数有值，并且value>=设置的参数值，则返回true
                if (!StringUtils.isEmpty(param)) {
                    int value = Integer.parseInt(param);
                    if(value < config.getValue() ){
                        return false;
                    }
                    return true;
                } else {
                    return false;
                }
            }
            public Object getConfig() {
                return config;
            }
        };
    }

    @Validated
    public static class Config {
        private @NotEmpty String param;
        private Integer value;

        public Config() {}

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }
    }
}
